/**
 * @author goufahui 1344116821@qq.com
 * @version 0.0.4
 * @description axios文件
 */
import axios from 'axios'
import Cookies from "vue-cookies";
import { Loading } from 'element-ui'

// 创建axios实例
var instance = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? '/api-inner/mid' : '/api',
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true, // 允许携带cookie
  timeout: 30000,
})
let loadingInstance

function startLoading() {
  // 开始加载
  loadingInstance = Loading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)',
  })
}

function endLoading() {
  // 结束加载
  loadingInstance.close()
}

// 添加request拦截器
instance.interceptors.request.use(
  (config) => {
    if (!config.showLoading) {
      startLoading()
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
// 添加response拦截器
instance.interceptors.response.use(
  (response) => {
    endLoading()
    const { code } = response.data
    switch (code) {
      case 201:
        // 清除用户信息
        Cookies.remove('mid_token', null, JSON.parse(sessionStorage.userInfo).cookieDomain)
          sessionStorage.clear()
        window.location.href = '/platform'
        break
    }
    return Promise.resolve(response.data)
  },
  (error) => {
    endLoading()
    return Promise.reject(error.response)
  }
)
export default instance
